﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using eloamComLib;
using System.Globalization;
using System.Timers;
using System.Threading;
using System.IO;
using System.Data.OracleClient;
using System.Configuration;
using System.Text.RegularExpressions;

namespace EloamComDemo
{
    public partial class Form1 : Form
    {
        private EloamGlobal global;
        private EloamVideo m_pVideo;
        private int m_timerValue;
        private EloamVideoCap m_pVideoCap;

        private EloamImage m_globalTempImage;

        public EloamMemory m_pTemplate;
        public EloamMemory m_pFeature;

        bool hasClickOcrList = false;
        //定义系统计时器
        private System.Timers.Timer timer;

        //设备列表
        private List<EloamDevice> m_deviceList;

        private bool isFirstLoad = true;
        ServiceOrcl.Scanner client = new ServiceOrcl.Scanner();
        private string ftpUrl = ConfigurationManager.AppSettings["ftpUrl"];
        private string userName = ConfigurationManager.AppSettings["userName"];
        private string passWord = ConfigurationManager.AppSettings["passWord"];
        private string type = ConfigurationManager.AppSettings["UploadType"] ?? "1";
        public Form1()
        {
            InitializeComponent();
            global = new EloamGlobal();
            m_deviceList = new List<EloamDevice>();

            m_pFeature = null;
            m_pTemplate = null;
            m_pVideoCap = null;

            FormInit();

            Init();
            BindListBox();
            BindComboBox();

        }
        public void FormInit()
        {
            //传入设备状态改变事件
            global.DevChange += DevChangeEventHandler;
            //传入移动监测事件
            global.MoveDetec += MoveDetecEventHandler;
            //视频播放事件
            global.Arrival += ArrivalEventHandler;
            //二代证
            global.IdCard += IdCardEventHandler;
            //Ocr识别事件
            global.Ocr += OcrEventHandler;

            //初始化设备
            global.InitDevs();

            if (!global.InitIdCard())
            {
                button_StartIdCardRead.Enabled = false;
                button_StopReadIDCard.Enabled = false;
            }

            if (global.InitBarcode())
            {
                barcode.Enabled = true;
            }
            else
            {
                barcode.Enabled = false;
            }

            if (global.InitOcr())
            {
                ocr.Enabled = true;
                ocrList.Enabled = true;
            }

            if (global.VideoCapInit())
            {
                startRecord.Enabled = true;
                stopRecord.Enabled = true;
            }
            else
            {
                startRecord.Enabled = false;
                stopRecord.Enabled = false;
            }
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            closeVideo_Click(new object(), new EventArgs());

            int count = m_deviceList.Count;
            if (count != 0)
            {
                for (int i = 0; i < count; i++)
                {
                    m_deviceList[i].Destroy();
                }
            }
            m_deviceList.Clear();

            global.DeinitBarcode();

            if (null != m_pTemplate)
            {
                m_pTemplate.Destroy();
                m_pTemplate = null;
            }
            if (null != m_pFeature)
            {
                m_pFeature.Destroy();
                m_pFeature = null;
            }

            if (m_pVideoCap != null)
            {
                m_pVideoCap.VideoCapStop();
                m_pVideoCap.Destroy();
                m_pVideoCap = null;
            }

            global.DeinitBiokey();
            global.DeinitIdCard();
            global.DeinitDevs();
            global.DeinitOcr();

            //传出设备状态改变事件
            global.DevChange -= DevChangeEventHandler;
            //传出移动监测事件
            global.MoveDetec -= MoveDetecEventHandler;
            //传出视频播放事件
            global.Arrival -= ArrivalEventHandler;
            //传出二代证
            global.IdCard -= IdCardEventHandler;
            //传出Ocr识别事件
            global.Ocr -= OcrEventHandler;
            System.Environment.Exit(0);
        }

        //设备状态改变事件响应
        public void DevChangeEventHandler(int type, int idx, int dbt)
        {
            if (1 == type)
            {
                if (1 == dbt)//设备到达
                {
                    EloamDevice tempDevice = (EloamDevice)global.CreateDevice(1, idx);
                    m_deviceList.Add(tempDevice);

                    selectDevice.Items.Add(tempDevice.GetFriendlyName());
                    if (-1 == selectDevice.SelectedIndex)
                    {
                        selectDevice.SelectedIndex = 0;//改变所选设备
                    }

                }
                else if (2 == dbt)//设备丢失
                {
                    EloamDevice tempDevice = m_deviceList[idx];
                    if (null != m_pVideo)
                    {
                        EloamDevice tempDevice2 = (EloamDevice)m_pVideo.GetDevice();
                        if (tempDevice == tempDevice2)
                        {
                            closeVideo_Click(new object(), new EventArgs());
                        }
                    }

                    m_deviceList[idx].Destroy();
                    m_deviceList.RemoveAt(idx);
                    selectDevice.Items.RemoveAt(idx);
                    if (-1 == selectDevice.SelectedIndex)
                    {
                        if (0 != m_deviceList.Count)
                        {
                            selectDevice.SelectedIndex = 0;
                        }
                        else
                        {
                            selectDevice.Items.Clear();
                            selectMode.Items.Clear();
                            selectResolution.Items.Clear();
                        }
                    }
                }
            }
        }

        //二代证事件响应
        public void IdCardEventHandler(int ret)
        {
            // Fire_MoveDetec
            StringBuilder MyStringBuilder = new StringBuilder();

            for (int i = 0; i < 16; i++)
            {
                string read;
                read = global.GetIdCardData(i + 1);
                MyStringBuilder.Append(read);
                MyStringBuilder.Append("\r\n");
            }
            string show = MyStringBuilder.ToString();
            EloamImage img = (EloamImage)global.GetIdCardImage(1);
            img.Save("idcard.jpg", 0);
            img.Destroy();
            MessageBox.Show(show);
        }

        //移动监测事件响应
        public void MoveDetecEventHandler(object pVideo, int id)
        {
            // Fire_MoveDetec
            shoot_Click(new object(), new EventArgs());
        }

        //视频播放事件
        private void ArrivalEventHandler(object pVideo, int id)
        {
            if (0 == id)//视频第一帧
            {
                openVideo.Enabled = false;
                closeVideo.Enabled = true;
                turnLeft.Enabled = true;
                turnRight.Enabled = true;
                exchangeLeftRight.Enabled = true;
                exchangeUpDown.Enabled = true;
                openProperty.Enabled = true;

                rectify.Enabled = true;
                rectify.Checked = true;
                removeGround.Enabled = true;
                autoShoot.Enabled = true;

                openTimer.Enabled = true;
                edit_Timer.Enabled = true;

                compoundShoot.Enabled = true;

                pictureSavePath.Enabled = true;
                shoot.Enabled = true;
                impdata.Enabled = true;

                barcode.Enabled = true;
            }
        }

        //Ocr识别事件
        private void OcrEventHandler(int flag, int ret)
        {
            if (hasClickOcrList)//只在识别列表时生效
            {
                if (1 == flag)
                {
                    if (0 == ret)
                    {
                        global.SaveOcr("D://ocrList.pdf", 0);
                        MessageBox.Show("识别成功！");
                    }
                    if (-1 == ret)
                    {
                        MessageBox.Show("识别失败！");
                    }
                    hasClickOcrList = false;
                }
                if (2 == flag)
                {
                    OcrPercentage.Text = ret.ToString() + "%";
                }
            }
        }
        private void openVideo_Click(object sender, EventArgs e)
        {
            int devIdx = selectDevice.SelectedIndex;
            string curModeString = selectMode.SelectedItem.ToString();
            int modeIdx = (curModeString == "YUY2" ? 1 :
                            (curModeString == "MJPG" ? 2 :
                                (curModeString == "UYVY" ? 4 :
                                    -1)));
            int resIdx = selectResolution.SelectedIndex;

            if (-1 != devIdx)
            {
                if (null != m_pVideo)
                {
                    m_pVideo.Destroy();
                    m_pVideo = null;
                }

                EloamDevice tempDevice = m_deviceList[devIdx];
                m_pVideo = (EloamVideo)tempDevice.CreateVideo(resIdx, modeIdx);

                if (null != m_pVideo)
                {
                    eloamView.SelectVideo(m_pVideo);
                    eloamView.SetText("打开视频中，请等待...", RGB(255, 255, 255));

                    selectDevice.Enabled = false;
                    selectResolution.Enabled = false;
                    selectMode.Enabled = false;

                    openVideo.Enabled = false;
                    closeVideo.Enabled = true;
                }
            }
        }

        public uint RGB(uint r, uint g, uint b)
        {
            return (((b << 16) | (g << 8)) | r);
        }

        private void closeVideo_Click(object sender, EventArgs e)
        {
            if (null != m_pVideo)
            {
                eloamView.SetText(null, 0);
                m_pVideo.Destroy();
                m_pVideo = null;
            }

            eloamView.SetText(null, 0);

            Reset();
        }
        public void Reset()
        {
            Init();
        }
        public void Init()
        {
            selectDevice.Enabled = true;
            selectResolution.Enabled = true;
            selectMode.Enabled = true;

            openVideo.Enabled = true;
            closeVideo.Enabled = false;
            turnLeft.Enabled = false;
            turnRight.Enabled = false;
            exchangeLeftRight.Enabled = false;
            exchangeUpDown.Enabled = false;
            openProperty.Enabled = false;

            rectify.Enabled = false;
            rectify.Checked = false;
            removeGround.Enabled = false;
            removeGround.Checked = false;
            autoShoot.Enabled = false;
            autoShoot.Checked = false;

            openTimer.Enabled = false;
            openTimer.Checked = false;
            edit_Timer.Enabled = false;

            compoundShoot.Enabled = false;
            compoundShoot.Checked = false;

            pictureSavePath.Enabled = false;
            shoot.Enabled = false;
            impdata.Enabled = false;

            m_timerValue = 5;
            edit_Timer.Text = m_timerValue.ToString();
            pictureSavePath.Text = "D:/PZ/";

            barcode.Enabled = false;
        }


        private void openProperty_Click(object sender, EventArgs e)
        {
            if (null != m_pVideo)
            {
                EloamDevice tempDevice = (EloamDevice)m_pVideo.GetDevice();
                tempDevice.ShowProperty(eloamView.GetView());
            }
        }


        private void rectify_CheckedChanged(object sender, EventArgs e)
        {
            if (null != m_pVideo)
            {
                if (rectify.Checked)
                {
                    m_pVideo.EnableDeskew(0);
                }
                else
                {
                    m_pVideo.DisableDeskew();
                }
            }
        }

        private void removeGround_CheckedChanged(object sender, EventArgs e)
        {
            if (null != m_pVideo)
            {
                if (removeGround.Checked)
                {
                    m_pVideo.EnableDelBkColor(0);
                }
                else
                {
                    m_pVideo.DisableDelBkColor();
                }
            }
        }

        private void autoShoot_CheckedChanged(object sender, EventArgs e)
        {
            if (null != m_pVideo)
            {
                if (autoShoot.Checked)
                {
                    m_pVideo.EnableMoveDetec(0);
                }
                else
                {
                    m_pVideo.DisableMoveDetec();
                }
            }
        }

        private void compoundShoot_CheckedChanged(object sender, EventArgs e)
        {
            if (compoundShoot.Checked)
            {
                if (null != m_globalTempImage)
                {
                    m_globalTempImage.Destroy();
                    m_globalTempImage = null;
                }
            }
        }
        private void shoot_Click(object sender, EventArgs e)
        {
            if (comboBox1.Text == "请选择证件类型")
            {
                comboBox1.Focus();
                MessageBox.Show("请选择证件类型");
                return;
            }
            if (null == m_pVideo)
            {
                return;
            }

            EloamView tempView = (EloamView)eloamView.GetView();
            EloamImage tempImage = (EloamImage)m_pVideo.CreateImage(0, tempView);

            if (null != tempImage)
            {

                DateTime dateTime = DateTime.Now;
                string time = DateTime.Now.ToString(
                    "yyyyMMdd_HHmmss_fff", DateTimeFormatInfo.InvariantInfo);
                string filename = pictureSavePath.Text + "\\" + listBox1.SelectedValue.ToString() + "\\" + comboBox1.Text + "\\Manual_" + time + ".jpg";

                if (compoundShoot.Checked)//合成拍照
                {
                    if (null == m_globalTempImage)
                    {
                        m_globalTempImage = tempImage;
                        MessageBox.Show("<合成拍摄中...> 请放下一张");
                    }
                    else
                    {
                        int w1 = m_globalTempImage.GetWidth();
                        int w2 = tempImage.GetWidth();
                        int width = (w1 > w2) ? w1 : w2;
                        int h1 = m_globalTempImage.GetHeight();
                        int h2 = tempImage.GetHeight();
                        int height = h1 + h2;

                        EloamImage compoundImage =
                            (EloamImage)global.CreateImage(width, height, 3);
                        if (null != compoundImage)
                        {
                            EloamRect rcDest1 = (EloamRect)global.CreateRect(0, 0, w1, h1);
                            EloamRect rcSrc1 = (EloamRect)global.CreateRect(0, 0, w1, h1);
                            compoundImage.Blend(rcDest1, m_globalTempImage, rcSrc1, 0, 0);

                            EloamRect rcDest2 = (EloamRect)global.CreateRect(0, h2, w2, h2);
                            EloamRect rcSrc2 = (EloamRect)global.CreateRect(0, 0, w2, h2);
                            compoundImage.Blend(rcDest2, tempImage, rcSrc2, 0, 0);
                            var directoryPath = Path.GetDirectoryName(filename);
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }
                            if (compoundImage.Save(filename, 0))
                            {
                                eloamView.PlayCaptureEffect();
                                eloamThumbnail.Add(filename);
                            }
                            else
                            {
                                MessageBox.Show("保存失败，请检查保存路径设置是否正确!");
                            }
                        }

                        m_globalTempImage.Destroy();
                        m_globalTempImage = null;
                    }

                }
                else
                {
                    var directoryPath = Path.GetDirectoryName(filename);
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    if (tempImage.Save(filename, 0))
                    {
                        eloamView.PlayCaptureEffect();
                        eloamThumbnail.Add(filename);
                        if (barcode.Checked)
                        {
                            global.DiscernBarcode(tempImage);
                            int count = global.GetBarcodeCount();
                            if (count > 0)
                            {
                                string strMsg = "";
                                for (int i = 0; i < count; ++i)
                                {
                                    strMsg += global.GetBarcodeData(i) + "\r\n";
                                }
                                MessageBox.Show(strMsg);
                            }
                            else
                            {
                                MessageBox.Show("识别条码失败");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("保存失败，请检查保存路径设置是否正确!");
                    }

                }

            }
        }


        private void turnLeft_Click(object sender, EventArgs e)
        {
            m_pVideo.RotateLeft();
        }

        private void turnRight_Click(object sender, EventArgs e)
        {
            m_pVideo.RotateRight();
        }

        private void exchangeLeftRight_Click(object sender, EventArgs e)
        {
            m_pVideo.Mirror();
        }

        private void exchangeUpDown_Click(object sender, EventArgs e)
        {
            m_pVideo.Flip();
        }

        private void openTimer_CheckedChanged(object sender, EventArgs e)
        {
            if (openTimer.Checked)
            {
                edit_Timer.Enabled = false;

                timer = new System.Timers.Timer();
                timer.Enabled = true;
                timer.Interval =
                    uint.Parse(edit_Timer.Text) * 1000;//单位为毫秒
                timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

            }
            else
            {
                timer.Stop();
                timer.Enabled = false;
                edit_Timer.Enabled = true;
            }
        }
        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            shoot_Click(sender, e);
        }

        private void selectDevice_SelectedIndexChanged(object sender, EventArgs e)
        {

            int idx = selectDevice.SelectedIndex;//记录当前所选设备

            selectMode.Items.Clear();

            if (-1 != idx)
            {
                EloamDevice tempDevice = m_deviceList[idx];

                //加载模式列表
                int subtype = tempDevice.GetSubtype();
                if (0 != (subtype & 1))
                {
                    selectMode.Items.Add("YUY2");
                }
                if (0 != (subtype & 2))
                {
                    selectMode.Items.Add("MJPG");
                }
                if (0 != (subtype & 4))
                {
                    selectMode.Items.Add("UYVY");
                }

                //若为辅摄像头，优先选择MJPG方式
                if (1 != tempDevice.GetEloamType() && (0 != (subtype & 2)) && (0 != (subtype & 1)))
                {
                    selectMode.SelectedIndex = 1;
                }
                else
                {
                    selectMode.SelectedIndex = 0;
                }

                openVideo.Enabled = true;
            }
            else
            {
                openVideo.Enabled = false;
            }
        }


        private void selectMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            int idx = selectDevice.SelectedIndex;//记录当前所选设备

            selectResolution.Items.Clear();

            if (-1 != idx)
            {
                EloamDevice tempDevice = m_deviceList[idx];
                //加载分辨率列表
                int subtype = -1;
                string curModeString = selectMode.SelectedItem.ToString();
                subtype = (curModeString == "YUY2" ? 1 :
                            (curModeString == "MJPG" ? 2 :
                                (curModeString == "UYVY" ? 4 :
                                    -1)));
                if (-1 != subtype)
                {
                    int count = tempDevice.GetResolutionCountEx(subtype);
                    for (int i = 0; i < count; ++i)
                    {
                        int width = tempDevice.GetResolutionWidthEx(subtype, i);
                        int height = tempDevice.GetResolutionHeightEx(subtype, i);

                        string str = width.ToString() + "*" + height.ToString();
                        selectResolution.Items.Add(str);
                    }
                    selectResolution.SelectedIndex = 0;
                }
            }
        }

        private void edit_Timer_TextChanged(object sender, EventArgs e)
        {
            try
            {
                uint.Parse(edit_Timer.Text);
            }
            catch (System.Exception)
            {
                MessageBox.Show("请输入一个正整数");
                edit_Timer.Text = "5";
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(() =>
            {
                if (null == m_pVideo)
                {
                    MessageBox.Show("视频未打开");
                    return;
                }
                EloamView tempView = (EloamView)eloamView.GetView();
                EloamImage tempImage = (EloamImage)m_pVideo.CreateImage(0, tempView);
                if (tempImage != null)
                {
                    global.DiscernOcr(1, tempImage);
                    global.WaitOcrDiscern();//同步等待
                    var fileFullName = "D://ocr.doc";
                    global.SaveOcr(fileFullName, 0);
                    MessageBox.Show("识别完成,保存路径为" + fileFullName);
                }
            });
            th.IsBackground = true;
            th.Start();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            EloamView tempView = (EloamView)eloamView.GetView();
            EloamImage tempImage = (EloamImage)global.CreateImageFromFile("D:\\1.jpg", 0);
            EloamImage tempImage2 = (EloamImage)global.CreateImageFromFile("D:\\2.jpg", 0);
            EloamImageList tempImageList = (EloamImageList)global.CreateImageList();
            if (tempImageList != null && tempImage != null && tempImage2 != null)
            {
                hasClickOcrList = true;

                tempImageList.Add(tempImage);
                tempImageList.Add(tempImage2);
                global.DiscernOcrList(1, tempImageList);//异步
            }
            else
            {
                MessageBox.Show("视频未打开");
            }
        }

        private void button_record_Click(object sender, EventArgs e)
        {
            if (null != m_pVideo)
            {
                int videoOutputWidth = m_pVideo.GetWidth();
                int videoOutputHeight = m_pVideo.GetHeight();
                //录像时，打开视频的分辨率越低，帧率越高,一般不超过200w像素
                //所设置的帧率应尽可能高于实际帧率，避免丢帧
                const int FrameRate = 15;//此参数可根据录像分辨率与机型实际帧率调节
                const int CheckWidth = 1600;
                const int CheckHeight = 1200;
                //主流视频分辨率少有大于200万的，因此为节约cpu资源，当分辨率大于200w，应采用200w的配置录制
                if ((videoOutputWidth * videoOutputHeight) > (CheckWidth * CheckHeight))
                {
                    MessageBoxButtons msgButton = MessageBoxButtons.YesNo;
                    DialogResult dr = MessageBox.Show(
                        "视频分辨率小于200万时，录制效果最佳，建议您切换到1600X1200或相近分辨率后继续录制视频",
                        "录像", msgButton);
                    if (dr == DialogResult.Yes)//如果点击“确定”按钮
                    {
                        return;
                    }
                    videoOutputWidth = CheckWidth;
                    videoOutputHeight = CheckHeight;
                }

                if (m_pVideoCap != null)
                {
                    m_pVideoCap.VideoCapStop();
                    m_pVideoCap.Destroy();
                    m_pVideoCap = null;
                }

                m_pVideoCap = (EloamVideoCap)global.CreatVideoCap();
                if (null == m_pVideoCap)
                {
                    MessageBox.Show("创建录像对象失败");
                    return;
                }

                int nSelectMic = -1;
                if (global.VideoCapGetAudioDevNum() > 0)//有麦克风
                {
                    nSelectMic = 0;
                }

                if (!m_pVideoCap.VideoCapPreCap(
                    "D://eloamVideo.mp4",
                    nSelectMic,
                    FrameRate,
                    1,
                    videoOutputWidth,
                    videoOutputHeight))
                {
                    MessageBox.Show("录像预处理失败");
                    return;
                }
                if (!m_pVideoCap.VideoCapAddVideoSrc(m_pVideo))
                {
                    MessageBox.Show("添加视频源失败");
                    return;
                }
                if (!m_pVideoCap.VideoCapStart())
                {
                    MessageBox.Show("开始录像失败");
                    return;
                }
                else
                {
                    MessageBox.Show("开始录像");
                }
            }
        }

        private void button__Click(object sender, EventArgs e)
        {
            if (null != m_pVideo)
            {
                if (null != m_pVideoCap)
                {
                    m_pVideoCap.VideoCapStop();
                    m_pVideoCap.Destroy();
                    m_pVideoCap = null;
                    MessageBox.Show("录像已停止，保存在D:/eloamVideo.mp4");
                }
            }
        }

        private void button_StartIdCardRead_Click(object sender, EventArgs e)
        {
            global.DiscernIdCard();
        }

        private void button_StopReadIDCard_Click(object sender, EventArgs e)
        {
            global.StopIdCardDiscern();
        }

        private delegate string DelegateGetFileName(string path, string iid);


        private void delete_Click(object sender, EventArgs e)
        {
            var list = new List<int>();
            for (int i = 0; i < eloamThumbnail.GetCount(); i++)
            {
                var isChecked = eloamThumbnail.GetCheck(i);
                if (isChecked) list.Add(i);
            }
            if (list.Count == 0)
            {
                MessageBox.Show("请勾选要删除的图片", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult dr = MessageBox.Show("确定要删除吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (dr != DialogResult.OK) return;
            //list.ForEach(i =>
            //{

            //});
            for (int i = eloamThumbnail.GetCount(); i >= 0; i--)
            {
                var isChecked = eloamThumbnail.GetCheck(i);
                if (isChecked)
                {
                    var fileFullName = eloamThumbnail.GetFileName(i);
                    var arrValue = fileFullName.Split('\\');
                    if (arrValue.Length >= 4)
                    {
                        var name = arrValue[arrValue.Length - 1];
                        var lb = arrValue[arrValue.Length - 2];
                        var iid = arrValue[arrValue.Length - 3];
                        if (type == "1")
                        {
                            if (client.DeleteImage(iid, name, lb))
                            {
                                eloamThumbnail.Remove(i, true);
                            }
                        }
                        else
                        {
                            var path = string.Concat("/Data/", iid, "/", lb, "/");
                            var isSuccess = client.DeleteFtpFile(ftpUrl, userName, passWord, path, name);
                            if (isSuccess)
                            {
                                eloamThumbnail.Remove(i, true);
                            }
                        }
                    }
                }
            }
        }

        private void impdata_Click(object sender, EventArgs e)
        {
            //Thread th = new Thread(() =>
            //{

            //});
            //th.IsBackground = true;
            //th.Start();
            if (comboBox1.Text == "请选择证件类型")
            {
                comboBox1.Focus();
                MessageBox.Show("请选择证件类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (null == m_pVideo)
            {
                return;
            }
            EloamView tempView = (EloamView)eloamView.GetView();
            EloamImage tempImage = (EloamImage)m_pVideo.CreateImage(0, tempView);

            if (null != tempImage)
            {
                DateTime dateTime = DateTime.Now;
                string time = DateTime.Now.ToString(
                    "yyyyMMdd_HHmmss_fff", DateTimeFormatInfo.InvariantInfo);
                string filename = pictureSavePath.Text + "\\" + listBox1.SelectedValue.ToString() + "\\" + comboBox1.Text + "\\Manual_" + time + ".jpg";

                if (compoundShoot.Checked)//合成拍照
                {
                    if (null == m_globalTempImage)
                    {
                        m_globalTempImage = tempImage;
                        MessageBox.Show("<合成拍摄中...> 请放下一张");
                    }
                    else
                    {
                        int w1 = m_globalTempImage.GetWidth();
                        int w2 = tempImage.GetWidth();
                        int width = (w1 > w2) ? w1 : w2;
                        int h1 = m_globalTempImage.GetHeight();
                        int h2 = tempImage.GetHeight();
                        int height = h1 + h2;

                        EloamImage compoundImage =
                            (EloamImage)global.CreateImage(width, height, 3);
                        if (null != compoundImage)
                        {
                            EloamRect rcDest1 = (EloamRect)global.CreateRect(0, 0, w1, h1);
                            EloamRect rcSrc1 = (EloamRect)global.CreateRect(0, 0, w1, h1);
                            compoundImage.Blend(rcDest1, m_globalTempImage, rcSrc1, 0, 0);

                            EloamRect rcDest2 = (EloamRect)global.CreateRect(0, h2, w2, h2);
                            EloamRect rcSrc2 = (EloamRect)global.CreateRect(0, 0, w2, h2);
                            compoundImage.Blend(rcDest2, tempImage, rcSrc2, 0, 0);
                            var directoryPath = Path.GetDirectoryName(filename);
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }
                            if (compoundImage.Save(filename, 0))
                            {
                                var iid = listBox1.SelectedValue.ToString();
                                SaveOrcl(iid, "", comboBox1.Text, filename);
                            }
                            else
                            {
                                MessageBox.Show("保存失败，请检查保存路径设置是否正确!");
                            }
                        }
                        m_globalTempImage.Destroy();
                        m_globalTempImage = null;
                    }
                }
                else
                {
                    var directoryPath = Path.GetDirectoryName(filename);
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    if (tempImage.Save(filename, 0))
                    {
                        var iid = listBox1.SelectedValue.ToString();
                        SaveOrcl(iid, "", comboBox1.Text, filename);
                        if (barcode.Checked)
                        {
                            global.DiscernBarcode(tempImage);
                            int count = global.GetBarcodeCount();
                            if (count > 0)
                            {
                                string strMsg = "";
                                for (int i = 0; i < count; ++i)
                                {
                                    strMsg += global.GetBarcodeData(i) + "\r\n";
                                }
                                MessageBox.Show(strMsg);
                            }
                            else
                            {
                                MessageBox.Show("识别条码失败");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("保存失败，请检查保存路径设置是否正确!");
                    }
                }
            }
        }

        /// <summary>
        /// 将文件转换为byte数组
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns>转换后的byte数组</returns>
        public byte[] File2Bytes(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return new byte[0];
            }
            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];
            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return buff;
        }

        /// <summary>
        /// 将byte数组转换为文件并保存到指定地址
        /// </summary>
        /// <param name="buff">byte数组</param>
        /// <param name="savepath">保存地址</param>
        public void Bytes2File(byte[] buff, string savepath)
        {
            if (System.IO.File.Exists(savepath))
            {
                return;
            }
            var directoryName = Path.GetDirectoryName(savepath);
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            using (FileStream fs = new FileStream(savepath, FileMode.CreateNew))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    bw.Write(buff, 0, buff.Length);
                }
            }
        }

        private void SaveOrcl(string iid, string userid, string lb, string filename)
        {
            try
            {
                var byteData = File2Bytes(filename);
                var fileName = Path.GetFileName(filename);
                if (type == "1")
                {
                    client.UploadEloam(byteData, iid, userid, lb, fileName);
                }
                else
                {
                    var strMsg = client.UploadFileToFtp(ftpUrl, userName, passWord, byteData, fileName, iid, userid, lb);
                    if (!string.IsNullOrWhiteSpace(strMsg))
                    {
                        MessageBox.Show("上传失败=>" + strMsg);
                        return;
                    }
                }
                eloamView.PlayCaptureEffect();
                eloamThumbnail.Add(filename);
            }
            catch (Exception ex)
            {
                MessageBox.Show("入库出错=>" + ex.Message);
            }
        }

        private void BindComboBox()
        {
            IList<Info> infoList = new List<Info>();
            var value = "请选择证件类型";
            infoList.Add(new Info() { Id = value, Name = value });
            var arrLb = client.GetLb();
            arrLb.ToList().ForEach(t =>
            {
                infoList.Add(new Info() { Id = t, Name = t });
            });
            comboBox1.DataSource = infoList;
            comboBox1.ValueMember = "Id";
            comboBox1.DisplayMember = "Name";
        }

        private void BindListBox()
        {
            var dataSet = client.GetIIDData();
            if (dataSet.Tables != null)
            {
                var dtTemp = dataSet.Tables[0];
                listBox1.DataSource = dtTemp;
                listBox1.ValueMember = dtTemp.Columns[0].ColumnName;
                listBox1.DisplayMember = dtTemp.Columns[0].ColumnName;
                isFirstLoad = false;
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isFirstLoad)
            {
                if (string.IsNullOrWhiteSpace(pictureSavePath.Text.Trim()))
                {
                    MessageBox.Show("拍照路径不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                eloamThumbnail.Clear(false);
                var iid = listBox1.SelectedValue.ToString();
                ServiceOrcl.Scanner client = new ServiceOrcl.Scanner();
                var directoryName = Path.Combine(pictureSavePath.Text, iid);
                if (type == "1")
                {
                    var list = client.GetEloamImg(iid);
                    list.ToList().ForEach(t =>
                    {
                        byte[] buffer = Convert.FromBase64String(t[0]);
                        string lb = t[1];
                        string name = t[2];
                        var fileName = Path.Combine(directoryName, lb, name);
                        Bytes2File(buffer, fileName);
                        eloamThumbnail.Add(fileName);
                    });
                }
                else
                {
                    var filePath = Path.Combine(pictureSavePath.Text, iid);
                    client.DownloadFileForDirectory(ftpUrl, userName, passWord, iid, directoryName);
                    if (!Directory.Exists(filePath)) return;
                    var arrDir = Directory.GetDirectories(filePath);
                    arrDir.ToList().ForEach(t =>
                    {
                        string[] filenames = Directory.GetFiles(t);
                        filenames.ToList().ForEach(f =>
                        {
                            if (File.Exists(f))
                            {
                                eloamThumbnail.Add(f);
                            }
                        });
                    });
                }

                //Thread th = new Thread(() =>
                //{

                //});
                //th.IsBackground = true;
                //th.Start();
            }
        }
    }

    public class Info
    {
        public string Id { get; set; }
        public string Name { get; set; }

    }
}

